package com.haobangs.imms.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.json.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;

import com.haobangs.imms.service.IControDeviceService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.http.ResponseEntity;

/**
 * 设备管理Service业务层处理
 *
 * @author haobangs
 * @date 2023-06-11
 */
@Service
public class ControDeviceServiceImpl implements IControDeviceService
{

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 查询报警的设备列表
     *
     * @param
     * @return 查询报警设备的结果
     */
    @Override
    public List<Map<String, Object>> getAlarmlist() throws JSONException {
        String accessToken;
        accessToken = getAccessTokenUsingClientCredentials("340fd46c817e4e39bd8eb26419a95581", "2fe64c6d8288497582f3e24bd2ea28f1");
        String url = "http://fbcs101.fbox360.com/api/v2/box/dmon/grouped?apiBaseUrl={apiBaseUrl}&Uid={Uid}&boxNo={boxNo}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);


        RestTemplate restTemplate = new RestTemplate();

        headers.set("Authorization", "Bearer "+accessToken); // 请替换为实际的access token

        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 设置请求参数
        String apiBaseUrl = "http://fbcs101.fbox360.com/api/v2/box/dmon/grouped";
        String Uid = "8968269919204994312"; // 请替换为实际的值
        String boxNo = "300223060424";

//         发起带有请求头的GET请求
//        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class, apiBaseUrl, Uid, boxNo);
//        if (response.getStatusCode() == HttpStatus.OK) {

            ParameterizedTypeReference<List<Map<String, Object>>> responseType = new ParameterizedTypeReference<List<Map<String, Object>>>() {};
            List<Map<String, Object>> responseBody = restTemplate.exchange(url, HttpMethod.GET, entity, responseType, apiBaseUrl, Uid, boxNo).getBody();

            List<Map<String, Object>> items = (List<Map<String, Object>>) responseBody.get(0).get("items");

            // 现在你可以直接返回items，而不需要手动进行JSON解析
            return items;
//        } else {
//            // 处理错误情况
//            return null;
//        }


    }

    /**
     * 删除报警记录信息
     *
     * @param deviceSerialNumber 设备编号例如“imms_2”
     * @return 结果代码，返回200代表成功
     */
    @Override
    public int Controldevice(String deviceSerialNumber){

        return 200;
    };


    public String getAccessTokenUsingClientCredentials(String clientId, String clientSecret) throws JSONException {
        String url = "https://account.flexem.com/core/connect/token";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("scope", "fbox");
        map.add("client_id", clientId);
        map.add("client_secret", clientSecret);
        map.add("grant_type", "client_credentials");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {

            // 解析 JSON 响应并提取 access_token
            String responseBody = response.getBody();

            // 将JSON字符串转换为JSONObject
            JSONObject jsonObject = new JSONObject(responseBody);

            // 提取access_token字段的值
            String accessToken = jsonObject.getString("access_token");

            return accessToken;
//          return "11111";
        } else {
            // 处理错误情况
            return null;
        }
    }

}
